//the stack keeps files on a stack for download

var express = require('express');
var app = module.exports = express();
var fs = require('fs');

// '/stack/:file?'
app.get('/:file?', function(req, res, next) {
    if(!req.params.file) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        fs.readdir(__dirname + '/stack/content', 
                   function(err, files) {
                       if(err) {
                           next(err);
                       }
                       else {
                           console.log(files);
                           var stack = [];
                           for(var i=0; i<files.length; i++) {
                               stack[i] = "<a href='/stack/content/" + files[i] + "'>" + files[i] + "</a><br />";
                           }
                           res.end('The Stack<br />'+stack.join(''));
                       }
                   });
        return; 
    }


    //res.download(__dirname + '/stack/' + req.params.file);
});

app.use(function(err, req, res, next) {
    if(err.code == 'ENOENT') {
        res.send('That file is not currently on the stack!');
        return;
    }

    console.error('*stack* ' + err.stack);
    res.send(500, 'Internal Server Error! Please tell me about this!');
});
